package com.ziytek.web.citizen.service.impl;

import cn.idev.excel.util.StringUtils;
import com.ziytek.web.citizen.caffeine.CaffeinePut;
import com.ziytek.web.citizen.config.ConfigInit;
import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.mapper.BasicCabinetIpMapper;
import com.ziytek.web.citizen.service.itf.CabinetNoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author fenghx
 * @version 1.0
 * @className CabinetNoServiceImpl
 * Description:
 * @date 2024/3/29 16:36
 */

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CabinetNoServiceImpl implements CabinetNoService {
    private final ConfigInit configInit;
    private final BasicCabinetIpMapper cabinetIpMapper;
    private final CaffeinePut caffeinePut;

    @Override
    public List<String> ipList() {
        List<String> ipQueryList = getStringList();
        if (CollectionUtils.isEmpty(ipQueryList)) {
            return Collections.emptyList();
        }

        var cabinetNoLists = cabinetIpMapper.queryCabinetNoByIp(ipQueryList);
        List<Integer> noNumList = new ArrayList<>();
        cabinetNoLists.forEach(t -> noNumList.add(Integer.parseInt(t.getCabinetNo())));
        noNumList.sort(Integer::compareTo);
        List<String> noList = new ArrayList<>();
        noNumList.forEach(t -> noList.add(String.valueOf(t)));
        return noList;
    }

    @Override
    public List<String> getStringList() {
        var ipList = caffeinePut.channelContextKeys();
        if (!configInit.isTest() && CollectionUtils.isEmpty(ipList)) {
            return Collections.emptyList();
        }
        List<String> list = new ArrayList<>(ipList);
        if (configInit.isTest()) {
            list.add(CaffeineUtil.IP_CACHE_PREFIX + "10.1.1.102");
        }

        List<String> ipQueryList = new ArrayList<>();
        list.forEach(t -> {
            if (!StringUtils.isEmpty(t)) {
                var ip = t.split(CaffeineUtil.IP_CACHE_PREFIX)[NumConstant.INT_ONE];
                if (!StringUtils.isEmpty(ip)) {
                    ipQueryList.add(ip);
                }
            }
        });

        return ipQueryList;
    }
}
